//
//  AppDelegate.m
//  ShopCart&FMDB
//
//  Created by 肖曙 on 17/4/11.
//  Copyright © 2017年 xiaoshu. All rights reserved.
//

#import "AppDelegate.h"
#import "RootController.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //OC需要添加的代码
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    RootController * rootView = [[RootController alloc]init];
    UINavigationController * nav = [[UINavigationController alloc]initWithRootViewController:rootView];
    self.window.rootViewController = nav;
    
    [self createFMDataBase];
    // Override point for customization after application launch.
    return YES;
}
#pragma mark - FMDB的建表
-(void)createFMDataBase{
    
    // 1.获得数据库文件的路径
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filename = [doc stringByAppendingPathComponent:@"shopCart.db"];
    NSLog(@"数据库地址:%@",filename);
    
    // 2.得到数据库
    FMDatabase *db = [FMDatabase databaseWithPath:filename];
    if ([db open]) {
        // 4.创表
        BOOL result = [db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_shopCart (id integer PRIMARY KEY AUTOINCREMENT, goodsName text NOT NULL, goodsID text NOT NULL, goodsPrice text NOT NULL, goodsCount integer NOT NULL);"];
        if (result) {
            NSLog(@"成功创表");
        } else {
            NSLog(@"创表失败");
        }
        [db close];
    }
    self.shopCartdb = db;
}
#pragma mark - FMDB的增删改查
//删除购物车全部数据
- (void)deleteAllDateFromShopCartFMDB{
    NSString *deleteSql=@"delete from t_shopCart";
    BOOL success=[self.shopCartdb executeUpdate:deleteSql];
    if (success) {
        
        NSLog(@"删除成功");
        
    } else {
        
        NSLog(@"删除失败");
        
    }
}
//插入一条数据
- (void)insertDateToShopCartFMDB:(GoodsModel *)goodsModel{
    if ([self.shopCartdb open]) {
        NSLog(@"%@%@%f",goodsModel.goodsName, goodsModel.goodsID,goodsModel.goodsSalePrice);
        NSString *insertsql=@"INSERT INTO t_shopCart (goodsName, goodsID, goodsPrice, goodsCount) VALUES (?, ?, ?, ?);";
        BOOL success = [self.shopCartdb executeUpdate:insertsql,[NSString stringWithFormat:@"%@",goodsModel.goodsName] ,[NSString stringWithFormat:@"%@",goodsModel.goodsID] ,[NSString stringWithFormat:@"%.2f",goodsModel.goodsSalePrice],@(1)];
        if (success) {
            
            NSLog(@"插入成功");
            
        } else {
            
            NSLog(@"插入失败");
            
        }
    }
}
//删除一条数据
- (void)deleteOneDataFromShopCartFMDB:(GoodsModel *)goodsModel{
    if ([self.shopCartdb open]) {
        FMResultSet *result = [self.shopCartdb executeQuery:@"select * from t_shopCart"];
        NSLog(@"===%@",goodsModel.goodsID);
        while ([result next]) {
            
            if ([[result stringForColumn:@"goodsID"] isEqualToString:goodsModel.goodsID]) {
                
                if ([[result stringForColumn:@"goodsCount"] isEqualToString:@"1"]) {
                    BOOL success = [self.shopCartdb executeUpdate:@"delete from t_shopCart where goodsID = ?;",goodsModel.goodsID];
                    if (success) {
                        
                        NSLog(@"删除成功");
                        
                    } else {
                        
                        NSLog(@"删除失败");
                        
                    }
                    break;
                }else{
                    
                    BOOL success = [self.shopCartdb executeUpdate:@"update t_shopCart set goodsCount = goodsCount-1 where goodsID = ?;",goodsModel.goodsID];
                    
                    if (success) {
                        
                        NSLog(@"数量减1");
                        
                    } else {
                        
                        NSLog(@"修改失败");
                        
                    }
                    break;
                }
            }
        }
        NSLog(@"%d",[self.shopCartdb intForQuery:@"select goodsCount from t_shopCart where goodsID = ?;",goodsModel.goodsID]);
        [self.shopCartdb close];
    }
}
//查询指定数据
- (void)queryDataFromShopCartFMDB:(GoodsModel *)goodsModel{
    if ([self.shopCartdb open]) {
        NSUInteger rowsCount = [self.shopCartdb intForQuery:@"select count(*) from t_shopCart"];
        if (rowsCount == 0) {
            [self insertDateToShopCartFMDB:goodsModel];
        }
        else{
            int i = 0;
            FMResultSet *result = [self.shopCartdb executeQuery:@"select * from t_shopCart"];
            NSLog(@"%@",result);
            while ([result next]) {
                i++;
                if ([[result stringForColumn:@"goodsID"] isEqualToString:[NSString stringWithFormat:@"%@",goodsModel.goodsID]]) {
                    BOOL success = [self.shopCartdb executeUpdate:@"update t_shopCart set goodsCount = goodsCount+1 where goodsID = ?;",goodsModel.goodsID];
                    if (success) {
                        
                        NSLog(@"数据加1");
                        
                    } else {
                        
                        NSLog(@"失败");
                        
                    }
                    break;
                }else{
                    NSLog(@"i = %i  rowsCount = %li",i,rowsCount);
                    if (i == rowsCount) {
                        [self insertDateToShopCartFMDB:goodsModel];
                        break;
                    }
                }
            }
        }
        //查找某个商品的数量
        NSLog(@"===%@===",goodsModel.goodsID);
        NSLog(@"%d",[self.shopCartdb intForQuery:@"select goodsCount from t_shopCart where goodsID = ?;",goodsModel.goodsID]);
        [self.shopCartdb close];
    }
}
//查询全部数据
- (NSMutableArray *)queryAllDataFromShopCartFMDB{
    NSMutableArray * array = [NSMutableArray new];
    if ([self.shopCartdb open]) {
        FMResultSet *result = [self.shopCartdb executeQuery:@"select * from t_shopCart"];
        int i = 0;
        while ([result next]) {
            i++;
            GoodsModel * model = [[GoodsModel alloc]init];
            model.goodsName = [result stringForColumn:@"goodsName"];
            model.goodsID = [result stringForColumn:@"goodsName"];
            model.goodsSalePrice = [[result stringForColumn:@"goodsPrice"]doubleValue];
            model.orderCount = [[result stringForColumn:@"goodsCount"]intValue];
            [array addObject:model];
        }
        NSLog(@"=====%d",i);
        NSUInteger rowsCount = [self.shopCartdb intForQuery:@"select count(*) from t_shopCart"];
        NSLog(@"%ld%ld",array.count,rowsCount);
        [self.shopCartdb close];
    }
    return array;
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
